package controls

import (
	"encoding/json"
	"github.com/labstack/echo/v4"
	"io/ioutil"
	"sofuny/config"
	"sofuny/utils"
)

// 设置
func AdminSettings(ctx echo.Context) error {

	var app = config.App()

	app.Password = utils.Base64Encode(app.Password)

	app.Database.Password = utils.Base64Encode(app.Database.Password)

	return ctx.JSON(200, utils.Response{
		Code:  200,
		Msg:   "success",
		Data:  app,
		Total: 1,
		Time:  utils.FormatTime(),
	})
}

// 修改设置
func AdminChangeSettings(ctx echo.Context) error {
	var app config.Config
	// 绑定数据
	if err := ctx.Bind(&app); err != nil {
		return ctx.JSON(200, utils.Response{
			Code:  201,
			Msg:   utils.DataBindErrorMessage,
			Data:  err,
			Total: 1,
			Time:  utils.FormatTime(),
		})
	}
	app.Password = utils.Base64Decode(app.Password)
	app.Database.Password = utils.Base64Decode(app.Database.Password)
	// json to byte
	byteValue, err := json.MarshalIndent(app, "", "  ")
	if err != nil {
		return ctx.JSON(200, utils.Response{
			Code:  201,
			Msg:   "json to byte 失败",
			Data:  err,
			Total: 1,
			Time:  utils.FormatTime(),
		})
	}
	// 修改文件
	err = ioutil.WriteFile("./app.json", byteValue, 0644)
	if err != nil {
		return ctx.JSON(200, utils.Response{
			Code:  201,
			Msg:   "修改文件失败",
			Data:  err,
			Total: 1,
			Time:  utils.FormatTime(),
		})
	}
	// 成功
	return ctx.JSON(200, utils.Response{
		Code:  200,
		Msg:   "success",
		Data:  app,
		Total: 1,
		Time:  utils.FormatTime(),
	})
}
